<?php
/*
Copyright (c) 2011 Julien Tartarin <devzone@mailjet.com>

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
*/

/*
How to use ?

1. Copy the phpsendmail folder somewhere on your server. Make sure your PHP user can read them.
2. Configure your php.ini or httpd.conf with the following line : (not supported in .htaccess or ini_set)
	sendmail_path = /path/to/php /path/to/phpsendmail/sendmail.php --conf=/path/to/config.inc.php
3. Reload the configuration (apachectl graceful)
4. Test ! The mail() function should return true, otherwise see syslog for debug

Note: configuration file is read each time mail() is called, so changes are made in real-time.
Also, be careful not to break the script with a parse error or something, mail() would fail.

Tip #1: if you have multiple virtualhosts or php instances,
you can define different sendmail_path to use different SMTP relays

Tip #2: you can use another config file using the 5th parameter of mail()
mail(to, subject, content, headers, '--conf=/path/to/specialconf')
Note: only if no --conf is present in the sendmail_path already
*/

# You should not have to change anything below this line.

# Send errors to syslog
ini_set('display_errors', false);
ini_set('log_errors', true);
ini_set('error_log', 'syslog');

# Work with absolute paths
define('MY_DIR', dirname(__FILE__));
set_include_path(MY_DIR.':'.MY_DIR.'/PEAR');

# Include config file but set defaults first
# You do NOT need to edit these !
$config = array(
	'host' => 'localhost',
	'port' => 25,
	'tls' => false,
	'user' => '',
	'passwd' => '',
);

# Default config file
$config_file = 'config.inc.php';

foreach($argv as $arg) {
	if(substr($arg, 0, 7) == '--conf=') {
		$user_config_file = substr($arg, 7);
		if(is_readable($user_config_file)) {
			$config_file = $user_config_file;
			break; # Keep the first file only
		}
	}
}

require_once $config_file;

# Use some PEAR::Mail classes
require_once 'Mail/RFC822.php';
require_once 'Mail/mimeDecode.php';

# Use PHPMailer's SMTP class
require_once 'phpmailer/class.smtp.php';

# Email raw content is received through STDIN
$message = file_get_contents('php://stdin');
if(empty($message)) trigger_error('Message is empty', E_USER_ERROR);

# Get headers in order to build recipient list
$mmd = new Mail_mimeDecode($message);
$headers = $mmd->_parseHeaders($mmd->_header);

$recipients = array();

# Build recipient list with addresses found in multiple header fields
foreach($headers as $header) {
	if(preg_match('/^(To|Cc|Bcc|Cci)$/i', $header['name'])) {
		$list = Mail_RFC822::parseAddressList($header['value'], 'localhost', false, false);
		foreach($list as $recipient) {
			$recipients[] = $recipient->mailbox.'@'.$recipient->host;
		}
	}
}

$recipients = array_unique($recipients);
if(sizeof($recipients)<1) trigger_error('No recipient', E_USER_ERROR);

# Let's send the mail
# Method calls are quite self descriptive
# Triggers everywhere to make sure mail() returns false if there's a problem

$smtp = new SMTP();

$smtp->Connect($config['host'], $config['port'], 15)
	or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);

$smtp->Hello()
	or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);

if($config['tls'] == true) {
	$smtp->StartTLS()
		or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);
	
	$smtp->Hello()
		or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);
}

if(!empty($config['user']) && !empty($config['passwd'])) {
	$smtp->Authenticate($config['user'], $config['passwd'])
		or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);
}

$smtp->Mail(getenv('USER').'@'.getenv('HOST'))
	or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);

foreach($recipients as $recipient) {
	$smtp->Recipient($recipient)
		or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);
}

$smtp->Data($message)
	or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);

$smtp->Quit(true)
	or trigger_error(print_r($smtp->getError(), true), E_USER_ERROR);

# If we're still here, everything is fine. Exit 0
exit(0);
